package org.adit.spring.hibernate.dao;

import java.util.List;

import org.adit.spring.hibernate.entity.Acidente;
import org.hibernate.Session;
import org.hibernate.Transaction;
import org.hibernate.criterion.MatchMode;
import org.hibernate.criterion.Restrictions;

import br.com.caelum.vraptor.ioc.Component;

@Component
public class AcidenteDao {

	private final Session session;

	public AcidenteDao(Session session) {
		this.session = session;
	}

	public void salva(Acidente acidente) {
		Transaction tx = session.beginTransaction();
		session.save(acidente);
		tx.commit();
	}

	@SuppressWarnings("unchecked")
	public List<Acidente> listaTudo() {
		return this.session.createCriteria(Acidente.class).list();
	}

	public Acidente carrega(Long id) {
		return (Acidente) this.session.load(Acidente.class, id);
	}

	public void atualiza(Acidente acidente) {
		Transaction tx = session.beginTransaction();
		session.update(acidente);
		tx.commit();
	}

	public void remove(Acidente acidente) {
		Transaction tx = session.beginTransaction();
		this.session.delete(acidente);
		tx.commit();
	}

	@SuppressWarnings("unchecked")
	public List<Acidente> busca(String tipo) {
		return session.createCriteria(Acidente.class).add(Restrictions.ilike("tipo", tipo, MatchMode.ANYWHERE)).list();
	}

	public void recarrega(Acidente acidente) {
		session.refresh(acidente);
	}
}